from django.conf import settings
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView, CreateAPIView
from QQLoginTool.QQtool import OAuthQQ
from rest_framework import status
from .models import OAuthQQUser
from rest_framework_jwt.settings import api_settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from oauth.serializers import OAuthQQSerializer
from carts.utils import merge_cart_cookie_to_redis


# Create your views here.

class OAuthQQURLView(APIView):
    def get(self, request):
        # 接受前端传递的state
        next = request.query_params.get('next')
        if not next:
            next = '/'

        # 构建url
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        url = oauth.get_qq_url()

        # 返回url
        return Response(
            {'login_url': url}
        )


class OAuthQQView(CreateAPIView):
    serializer_class = OAuthQQSerializer

    def get(self, request):
        # 1.获取code
        code = request.query_params.get('code')
        if not code:
            return Response({'message': '缺少code值'}, status=status.HTTP_404_NOT_FOUND)

        # 2.根据code获取access token值
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,state=next)
        access_token = oauth.get_access_token(code)
        print('access_token值',access_token)

        # 3.根据access值获取openid
        openid = oauth.get_open_id(access_token)
        print('openid值',openid)

        # 4.判断openid是否绑定 需要查询数据库
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        # 如果数据库中没有该数据证明用户没有绑定过,而且会报错所以走到except证明要引导用户去绑定
        except:
            # openid要加密
            # 通过TimedJSONWebSignatureSerializer进行加密,第一项是随机字符串,第二项是有效期,单位是秒
            tjs = TJS(settings.SECRET_KEY, 300)
            # 通过dumps方法根据前面写的随机字符串进行加密
            token = tjs.dumps({'openid': openid}).decode()
            # 给前端发的这个token值是加密过的openid
            return Response({'access_token': token})

        # 如果openid绑定过则引导用户到登录成功页面
        user = qq_user.user

        # 生成token给前端存放到浏览器当中
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        response = Response(
            {
                'username': user.username,
                'token': token,
                'user_id': user.id
            })
        response = merge_cart_cookie_to_redis(request, response, user)

        return response

    # def post(self, request, *args, **kwargs):
    #     response = super().post(request, *args, **kwargs)
    #
    #     # 合并购物车
    #     response = merge_cart_cookie_to_redis(request, self.user, response)
    #     return response

    # def post(self, request, *args, **kwargs):
    #     response = super().post(request, *args, **kwargs)
    #
    #     response = merge_cart_cookie_to_redis(request, response, request.user)
    #     return response
